package de.bazinga.rotw.network;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import de.bazinga.rotw.util.NetworkConstants;

public class NetScanThread extends Thread
{
	private NetworkScan networkscan;
	private int netRangeBeginn;
	private String localIP;
	
	public NetScanThread(NetworkScan networkscan,int netRangeBeginn, String localIP)
	{
		this.networkscan = networkscan;
		this.netRangeBeginn = netRangeBeginn;
		this.localIP = localIP;
	}
	
	
	
	@Override
	public void run()
	{	
		if(localIP!=null)
		{
			//System.out.println("Scanning LAN..");
			String lanAddress = localIP.substring(0,localIP.lastIndexOf(".")+1);
			String tmpIpLieteral = null;
			int netRangeStop = netRangeBeginn+50;
			@SuppressWarnings("unused")
			Socket socket = null;
			
			for(int netRange=netRangeBeginn;netRange<=netRangeStop;netRange++)
			{
				if(Thread.interrupted())
				{
					System.out.println("Scanning stoped!");
					return;
				}
				tmpIpLieteral = lanAddress+String.valueOf(netRange).trim();				
				InetAddress tmpIpAddress;				
				try
				{
					tmpIpAddress=InetAddress.getByName(tmpIpLieteral);
					//InetSocketAddress remoteAddr = new InetSocketAddress(tmpIpAddress, NetworkConstants.SERVER_TCP_PORT);
				
					try				    
				    {
						/******************Here the client attemps to find a server****************************/
			    		socket = new Socket(tmpIpAddress,NetworkConstants.SERVER_TCP_PORT);
				    //	socket.connect(remoteAddr, NetworkConstants.LAN_SEARCH_TIMEOUT); // 255 * 100 = 25.500 mili sec => maximal 25,5 sec search time
				    	
				    	networkscan.hostFound(tmpIpLieteral);
				    }
				    catch(IOException ex)
				    {
				    	//System.out.println(tmpIpLieteral +" has no Server listening on Port "+NetworkConstants.SERVER_TCP_PORT);
				    }
				}
				catch (UnknownHostException e)
				{				
					System.out.println(tmpIpLieteral +" not found");
				}
			}
			//System.out.println("Finished scanning LAN!");
		}
	}
}
